<!--
 * new page
 * @author: denghao
 * @since: 2024-04-02
 * AudioCustom.vue
-->
<template>
  <audio
    ref="customAudio"
    preload="auto"
    :src="props.songUrl"
    @canplay="canplaySong"
    @pauseAudio="pauseAudio"
    @playing="startAudio"
    @ended="ended"
    @error="error"
    @timeupdate="updateSongTime"
  ></audio>
</template>

<script setup lang="ts">
import { useStore } from "vuex";
import { ref, reactive, defineExpose } from "vue";
/**
 * ---------类型---------
 */
interface infoFace {
  initAudioReady: Boolean;
  playMode: number;
}

interface propType {
  songUrl: string;
}
/**
 * ---------变量定义---------
 */
const customAudio = ref<HTMLAudioElement | null>(null);
const info = reactive<infoFace>({
  initAudioReady: false, // 初始化音频准备
  playMode: 0, // 播放模式  0循环播放、1单曲循环、2随机播放
});
const props = withDefaults(defineProps<propType>(), {});
const store = useStore();
/**
 * ---------方法---------
 */
const emits = defineEmits(["updateSongTime"]);
const canplaySong = () => {
  info.initAudioReady = true;
};
// 播放开始
const startAudio = () => {
  console.log("音频开始播放");
};
// 播放暂停
const pauseAudio = () => {
  console.log("音频暂停");
};
// 播放到媒体的结束位置，播放停止。
const ended = () => {};

const error = () => {
  console.error("音频加载失败");
};

//由 currentTime 指定的时间更新
const updateSongTime = (event: any) => {
  const { duration, currentTime } = event.target;
  console.log("更新音频时间", event);
  emits("updateSongTime", duration, currentTime);
};
// 音量禁音及取消操作
const volumeHandler = (muted: boolean) => {
  const audio = customAudio.value;
  if (audio) {
    audio.muted = muted;
  }
};
// 播放和暂停
const toggleAudio = () => {
  const audio = customAudio.value;
  if (audio) {
    if (audio.paused) {
      audio.play();
    } else {
      audio.pause();
    }
  }
};
//将子组件的方法暴露给父组件
defineExpose({
  toggleAudio,
  startAudio,
  pauseAudio,
  updateSongTime,
  volumeHandler,
});
</script>

<style scoped></style>
